package com.sniper.springmvc.action.admin;

import com.gentle.service.comply.TransdataService;
import com.gentle.service.declare.Exception_Exception;
import com.gentle.service.declare.IDataService;
import com.gentle.service.declare.JyzxBack;
import com.sniper.springmvc.jyzx.JyzxData;
import com.sniper.springmvc.jyzx.JyzxImportBack;
import com.sniper.springmvc.jyzx.JyzxUtils;
import com.sniper.springmvc.model.JyzxReceive;
import com.sniper.springmvc.mybatis.service.impl.JyzxReceiveService;
import com.sniper.springmvc.scheduler.JyzxImportWithScheduled;
import com.sniper.springmvc.searchUtil.ChannelSearch;
import com.sniper.springmvc.shiro.scheduler.QuartzManagerUtil;
import com.sniper.springmvc.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dom4j.DocumentException;
import org.quartz.SchedulerException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created by suzhen on 2017/4/3.
 */
@Controller
@RequestMapping("${adminPath}/admin-jyzx")
public class AdminJyzxController extends AdminBaseController {


    Map<Integer, String> types = new HashMap<>();

    public Map<Integer, String> getTypes() {
        types.put(JyzxReceiveService.TYPE_RECEIVE, "接收数据");
        types.put(JyzxReceiveService.TYPE_SEND, "反馈数据");
        return types;
    }

    @Resource
    JyzxReceiveService jyzxReceiveService;


    @RequiresPermissions("admin:jyzx:view")
    @RequestMapping("/")
    public String index(Map<String, Object> map, ChannelSearch search) throws IOException {

        map.put("sniperUrl", "/admin-jyzx/delete");
        ParamsToHtml toHtml = new ParamsToHtml();

        Map<String, Object> params = new HashMap<>();

        if (ValidateUtil.isValid(search.getName())) {
            params.put("entname", "%" + search.getName() + "%");
        }

        if (ValidateUtil.isValid(search.getItemid())) {
            params.put("type", search.getItemid());
        }

        if (ValidateUtil.isValid(search.getSubmit()) && search.getSubmit().equals("export")) {
            ExeclJyzxExportUtil exportUtils = new ExeclJyzxExportUtil();
            exportUtils.setRootDir(FilesUtil.getRootDir());
            //设置头部xx
            Map<String, String> valueMap = new LinkedHashMap<>();
            valueMap.put("id", "序号");
            valueMap.put("entname", "企业名称");
            valueMap.put("regno", "注册号");
            valueMap.put("uniscid", "社会统一信用代码");
            valueMap.put("regorgname", "部门");
            valueMap.put("noticefrom", "公告期自");
            valueMap.put("noticeto", "公告期至");
            valueMap.put("date", "接收日期");

            List<JyzxReceive> receives = jyzxReceiveService.query("select", params);
            String exportPath = FilesUtil.getSaveDir("") + "export.xlsx";
            exportUtils.export(exportPath, receives);
            // 直接文件下载
            String webUrl = FilesUtil.getWebUrl();
            if (!ValidateUtil.isValid(webUrl)) {
                webUrl = basePath;
            }
            return InternalResourceViewResolver.REDIRECT_URL_PREFIX + webUrl + exportPath;
        }

        PageUtil page = jyzxReceiveService.page(request, 50, params);
        map.put("page", page);
        map.put("sniperMenu", toHtml);
        map.put("search", search);
        map.put("types", getTypes());

        return forward("/admin/admin-jyzx/index.jsp");
    }


    /**
     * 更新展示,修改展示
     *
     * @param id
     * @param map
     * @return
     */
    @RequiresPermissions("admin:jyzx:show")
    @RequestMapping(value = "show", method = RequestMethod.GET)
    public String show(@RequestParam(value = "id", required = false) String id, Map<String, Object> map) {

        JyzxReceive receive = jyzxReceiveService.get(id);
        map.put("receive", receive);
        return forward("/admin/admin-jyzx/show.ftl");
    }


    /**
     * 更新展示,修改展示
     *
     * @param map
     * @return
     * @throws IOException
     */
    @RequiresPermissions("admin:jyzx:insert")
    @RequestMapping(value = "insert", method = RequestMethod.GET)
    public String insert(Map<String, Object> map) {

        map.put("receive", new JyzxReceive());
        return forward("/admin/admin-jyzx/save-input.jsp");
    }


    @RequiresPermissions("admin:jyzx:insert")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public String insert(JyzxReceive receive, BindingResult result, Map<String, Object> map) {
        List<String> msg = new ArrayList<>();
        TransdataService t = new TransdataService();
        try {
            if (result.getFieldErrorCount() == 0) {
                IDataService iDataService = t.getDataServicePort();
                JyzxBack back = new JyzxBack();
                BeanUtils.copyProperties(receive, back);
//                String a = iDataService.backJyzx(new ArrayList<JyzxBack>() {{
//                    add(back);
//                }});
                System.out.println(back);
                String a = null;
                JyzxData data = JyzxUtils.decodeStr(a);
                if (data.getCode().equals("success")) {
                    receive.setSuccess(true);
                    msg.add(data.getMsg());
                } else {
                    receive.setSuccess(false);
                    msg.add(data.getMsg());
                }
                map.put("error", map);
                receive.setType(JyzxReceiveService.TYPE_SEND);
                receive.setId(FilesUtil.UUID());
                jyzxReceiveService.insert(receive);
                if (receive.getSuccess() == false) {
                    return redirect("/admin-jyzx/update?id=" + receive.getId());
                }
            } else {
                for (FieldError error : result.getFieldErrors()) {
                    msg.add(error.getDefaultMessage());
                }
                map.put("error", map);
                map.put("receive", receive);
                return forward("/admin/admin-jyzx/save-input.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return redirect("/admin-jyzx/insert");
    }

    /**
     * 更新展示,修改展示
     *
     * @param id
     * @param map
     * @return
     */
    @RequiresPermissions("admin:jyzx:update")
    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String update(@RequestParam(value = "id", required = false) String id,
                         JyzxReceive receive, Map<String, Object> map) {


        return forward("/admin/admin-jyzx/save-input.jsp");
    }

    @RequiresPermissions("admin:jyzx:update")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(@Valid JyzxReceive receive, BindingResult result, Map<String, Object> map) {


        return redirect("/admin-jyzx/update?id=" + receive.getId());
    }

    /**
     * 删除
     *
     * @return
     */
    @RequiresPermissions("admin:jyzx:delete")
    @ResponseBody
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public Map<String, Object> delete(@RequestParam("delid") String[] delid,
                                      @RequestParam("menuType") String menuType,
                                      @RequestParam("menuValue") String menuValue) throws Exception_Exception, DocumentException {

        // code 小于1表示有错误,大于0表示ok,==0表示未操作
        Map<String, Object> ajaxResult = new HashMap<>();
        switch (menuType) {
            //删除
            case "delete":
                delete(ajaxResult, jyzxReceiveService, delid);
                break;
            //提交
            case "back":

                TransdataService t = new TransdataService();
                IDataService iDataService = t.getDataServicePort();
                List<JyzxBack> backs = new ArrayList<>();
                for (String id : delid) {
                    JyzxReceive receive = jyzxReceiveService.get(id);
                    BeanUtils.copyProperties(receive, backs);
                }
                String result = iDataService.backJyzx(backs);
                JyzxData data = JyzxUtils.decodeStr(result);

                if (data.getCode().equals("success")) {
                    for (String id : delid) {
                        JyzxReceive receive = jyzxReceiveService.get(id);
                        receive.setSuccess(true);
                        jyzxReceiveService.update(receive);
                    }
                    ajaxResult.put("code", 1);
                    ajaxResult.put("msg", "success");
                } else {
                    ajaxResult.put("code", -1);
                    ajaxResult.put("msg", "fail");
                }
                break;

            default:
                break;
        }
        return ajaxResult;
    }

    /**
     * 数据导入
     *
     * @return
     * @throws Exception_Exception
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws DocumentException
     * @throws InvocationTargetException
     */
    @RequiresPermissions("admin:jyzx:import")
    @RequestMapping(value = "import", method = RequestMethod.GET)
    public String importJyzx(Map<String, Object> map) {

        map.put("back", new JyzxImportBack());
        return forward("/admin/admin-jyzx/import.jsp");
    }


    @RequiresPermissions("admin:jyzx:import")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importJyzxPost(Map<String, Object> map) throws SchedulerException {

        QuartzManagerUtil.start();
        QuartzManagerUtil.addCronJob(JyzxImportWithScheduled.jobName, JyzxImportWithScheduled.class, "0 0 1 * * ?");
        //占位符
        map.put("back", new JyzxImportBack());
        return forward("/admin/admin-jyzx/import.jsp");
    }

}
